package com.lebang.medicalInquiry.utils;

import cn.hutool.crypto.PemUtil;
import lombok.SneakyThrows;
import okhttp3.HttpUrl;
import org.apache.http.impl.client.CloseableHttpClient;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class WxUtil {

    public String getToken(String appid, String nonceStr, String prepayid) {

        long timestamp = System.currentTimeMillis() / 1000;
        String message = buildMessage(appid, timestamp, nonceStr, prepayid);
        String signature = null;
        try {
            signature = sign(message.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        return signature;
    }

    public static PrivateKey getPrivateKey(String filename) throws IOException {

        String content = new String(Files.readAllBytes(Paths.get(filename)), "utf-8");
        try {
            String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "")
                    .replace("-----END PRIVATE KEY-----", "")
                    .replaceAll("\\s+", "");

            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(
                    new PKCS8EncodedKeySpec(Base64.decode(privateKey)));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持RSA", e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException("无效的密钥格式");
        }
    }

    public String sign(byte[] message) {

        Signature sign = null;
        try {
            sign = Signature.getInstance("SHA256withRSA");
            sign.initSign(getPrivateKey("ss"));
            sign.update(message);
            return Base64.encode(sign.sign());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public String buildMessage(String appId, long timestamp, String nonceStr, String prepayid) {


        return appId + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + prepayid + "\n";
    }


}
